package io.github.lee.app.unsplash.ui.main

import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.gyf.immersionbar.ktx.immersionBar
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.app.unsplash.R
import io.github.lee.app.unsplash.databinding.ActivityMainBinding
import io.github.lee.app.unsplash.ui.main.home.HomeFragment
import io.github.lee.app.unsplash.ui.main.search.MainSearchFragment
import io.github.lee.core.ui.BaseActivity
import io.github.lee.core.vm.BaseViewModel

@AndroidEntryPoint
class MainActivity : BaseActivity<ActivityMainBinding, BaseViewModel>() {

    override fun onCreateSuccess(): ActivityMainBinding =
        ActivityMainBinding.inflate(layoutInflater)

    //===Desc:======================================================================================

    override fun onSetViewListener() {
        super.onSetViewListener()
        vb?.apply {
            tabs.setOnItemSelectedListener {
                when (it.itemId) {
                    R.id.image -> vpContent.currentItem = 0
                    R.id.search -> vpContent.currentItem = 1
                    else -> throw IllegalAccessException("Unknown tab option")
                }
                true
            }
            vpContent.registerOnPageChangeCallback(object : OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    super.onPageSelected(position)
                    when (position) {
                        0 -> tabs.selectedItemId = R.id.image
                        1 -> tabs.selectedItemId = R.id.search
                    }
                }

            })
        }
    }

    override fun onSetViewData() {
        super.onSetViewData()
        immersionBar {
            transparentBar()
        }
        vb?.apply {
            vpContent.adapter = object : FragmentStateAdapter(this@MainActivity) {
                override fun getItemCount(): Int = 2

                override fun createFragment(position: Int): Fragment {
                    return when (position) {
                        0 -> HomeFragment.newInstance()
                        1 -> MainSearchFragment.newInstance()
                        else -> throw IllegalStateException("The main page is more than $itemCount pages")
                    }
                }
            }
            vpContent.setCurrentItem(0, false)
        }

        vb?.tabs?.selectedItemId = R.id.image

    }
}